package hxy.grandfather.live.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import hxy.grandfather.live.R;
import hxy.grandfather.live.launcher.AppListService;
import hxy.grandfather.live.launcher.PackageMod;
import hxy.grandfather.live.util.Constant;

public class HomeActivity extends Activity {

    Logger log = LoggerFactory.getLogger(HomeActivity.class);

    private List<PackageMod> allApp = new ArrayList<>();
    private PackageManager packageManager;
    private GridView mGrid;
    private String TAG = "live";
    public AppsAdapter adapter;
    private AppListService appListService;
    private SharedPreferences defaultSharedPreferences;


    /**
     * 注册广播，用来Service和Activity之间通信，用来数据加载之后刷新界面
     */
    private BroadcastReceiver receiver = null;


    private OnItemClickListener listener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            try {
                PackageMod info = allApp.get(position);
                startActivity(info.intent);
            } catch (Exception e) {
                log.error("桌面点击打开失败", e);
            }
        }
    };

    private BroadcastReceiver appReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "外部Receiver监听器" + intent.getAction());
            if ("android.intent.action.PACKAGE_CHANGED".equals(action) || "android.intent.action.PACKAGE_REMOVED".equals(action) || "android.intent.action.PACKAGE_ADDED".equals(action)) {
                HomeActivity.this.updateAppList(intent);
            }
        }
    };

    public void updateAppList(Intent intent) {
        String packageName;
        if (intent.getData() == null || !((packageName = intent.getData().getSchemeSpecificPart()) == null || packageName.length() == 0 || packageName.equals("com.android.provision"))) {
            displayShortcuts();
        }
    }

    /**
     * 刷新桌面图标
     */
    public void displayShortcuts() {
        allApp.clear();
        loadApps();
        loadLink();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        log.info("这个是logback打印的日志");
        final Intent serviceIntent = new Intent(getApplicationContext(), AppListService.class);
        bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
        Intent intent = new Intent(getBaseContext(), AppListService.class);
        startService(intent);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(intent);
//        } else {
//            startService(intent);
//        }

        IntentFilter filter = new IntentFilter("");
        Log.i(TAG, "注册appReceiver");
        registerReceiver(appReceiver, filter);
        loadApps();
        loadLink();
        setContentView(R.layout.activity_launcher);

        mGrid = (GridView) findViewById(R.id.apps_list);
        adapter = new AppsAdapter(HomeActivity.this);
        mGrid.setAdapter(adapter);

        mGrid.setOnItemClickListener(listener);


        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                log.info("内部Receiver监听器{}", action);
                switch (action) {
                    case Intent.ACTION_PACKAGE_ADDED:
                        String packageName = intent.getData().getSchemeSpecificPart();
                        log.info("--------安装成功={}", packageName);
                        try {

                            ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(packageName, 0);
                            ApplicationInfo applicationInfo1 = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);

                            Drawable drawable = applicationInfo.loadIcon(getPackageManager());
                            // TODO 这里获取的mainActivity不一定是真实的，很可能没有用
                            String mainActivity = applicationInfo.name != null ? applicationInfo.name : applicationInfo.className;
                            if (mainActivity != null) {
                                ComponentName component = new ComponentName(packageName, mainActivity);
                                Intent intent2 = new Intent();
                                intent2.setComponent(component);
                                String appName = applicationInfo.loadLabel(packageManager).toString();
                                PackageMod packageMod = new PackageMod(intent2, appName, drawable);
                                allApp.add(packageMod);
                            } else {
                                log.warn("{}这个软件加载到桌面失败,{}", packageName, applicationInfo.className);

                                log.warn("{},className=>{},packageName=>{}", applicationInfo1.name, applicationInfo1.className, applicationInfo1.packageName);
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            log.error("刷新桌面失败{}", e);
                        }
                        displayShortcuts();
                        break;
                    case Intent.ACTION_PACKAGE_REPLACED:
                        packageName = intent.getData().getSchemeSpecificPart();
                        log.info("--------更新成功{}", packageName);
                        break;
                    case Intent.ACTION_PACKAGE_REMOVED:
                        packageName = intent.getData().getSchemeSpecificPart();
                        log.info("--------卸载成功{}", packageName);
                        displayShortcuts();
                        break;
                    case Intent.ACTION_BOOT_COMPLETED:
                        // TODO 这里貌似没有生效
                        log.info("--------监听开机启动");
                        break;
                    default:
                        break;
                }
            }
        };

        IntentFilter filter1 = new IntentFilter(Constant.BROADCAST_ACTION);

        filter1.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter1.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter1.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter1.addAction(Intent.ACTION_BOOT_COMPLETED);
        filter1.addDataScheme("package");

        registerReceiver(receiver, filter1);
        log.info("内部Receiver注册");
    }

    // 返回键的监听
    @Override
    public void onBackPressed() {
        displayShortcuts();
        log.info("按下了back键，刷新桌面完成， onBackPressed()");
        Log.i(TAG, "按下了back键   onBackPressed()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        如果不取消就会造成内存泄露
        unregisterReceiver(receiver);//LS:重点！
        Log.i(TAG, "取消注册appReceiver");
        unregisterReceiver(appReceiver);//LS:重点！
        unbindService(mConnection);
    }


    /**
     * 加载所有系统应用
     */
    private void loadApps() {
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        packageManager = getPackageManager();
        List<ResolveInfo> mApps = packageManager.queryIntentActivities(mainIntent, 0);


        for (ResolveInfo resolveInfo : mApps) {
            Drawable drawable = resolveInfo.activityInfo.loadIcon(getPackageManager());
            String appName = resolveInfo.activityInfo.applicationInfo.loadLabel(packageManager).toString();


            //该应用的包名
            String packageName = resolveInfo.activityInfo.packageName;
            //应用的主activity类
            String mainActivity = resolveInfo.activityInfo.name;
            ComponentName component = new ComponentName(packageName, mainActivity);
            Intent intent = new Intent();
            intent.setComponent(component);

            PackageMod packageMod = new PackageMod(intent, appName, drawable);
            allApp.add(packageMod);
        }

        // 另一种获取应用程序的方式
        List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { //非系统应用
                // AppInfo 自定义类，包含应用信息
                Toast.makeText(getApplicationContext(), packageInfo.packageName, Toast.LENGTH_SHORT);
//                AppInfo appInfo = new AppInfo();
//                appInfo.setAppName(
//                        packageInfo.applicationInfo.loadLabel(getPackageManager()).toString());//获取应用名称
//                appInfo.setPackageName(packageInfo.packageName); //获取应用包名，可用于卸载和启动应用
//                appInfo.setVersionName(packageInfo.versionName);//获取应用版本名
//                appInfo.setVersionCode(packageInfo.versionCode);//获取应用版本号
//                appInfo.setAppIcon(packageInfo.applicationInfo.loadIcon(getPackageManager()));//获取应用图标
//                System.out.println(appInfo.toString());
//                mData.add(appInfo);
            }
        }
    }

    /**
     * 加载自己桌面的快捷方式
     */
    private void loadLink() {

        Intent settingIntent = new Intent(getApplicationContext(), SettingsActivity.class);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher_foreground);
        PackageMod packageMod = new PackageMod(settingIntent, "开机启动", drawable);
        allApp.add(packageMod);

        Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
        PackageMod aboutIntentPackageMod = new PackageMod(aboutIntent, "关于", drawable);
        allApp.add(aboutIntentPackageMod);

    }


    public class AppsAdapter extends BaseAdapter {

        private LayoutInflater inflater;

        public AppsAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            PackageMod packageMod = allApp.get(position);

            ViewHolder holder = null;
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.launcher_item, null);
                holder = new ViewHolder();
                holder.appImage = (ImageView) convertView.findViewById(R.id.app_icon);
                holder.appName = (TextView) convertView.findViewById(R.id.app_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

//            convertView.setBackgroundResource(R.drawable.shape_video_bg);
//            convertView.setPadding(10,10,10,10);

            holder.appImage.setImageDrawable(packageMod.icon);
            holder.appName.setText(packageMod.appName);

            // 获取屏幕的高度和宽度
            Display defaultDisplay = getWindowManager().getDefaultDisplay();
            Point point = new Point();
            defaultDisplay.getSize(point);
            convertView.setLayoutParams(new GridView.LayoutParams(point.x / 4, point.y / 4));

            return convertView;

        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            log.info("刷新桌面中");
        }

        public final int getCount() {
            return allApp.size();
        }

        public final Object getItem(int position) {
            return allApp.get(position);
        }

        public final long getItemId(int position) {
            return position;
        }
    }


    private final static class ViewHolder {
        ImageView appImage;
        TextView appName;
    }

    // 绑定服务
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            appListService = ((AppListService.LocalBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            appListService = null;
        }
    };


}